const Base = require('./base.js');

module.exports = class extends Base {
  async loginAction() {
    const username = this.post('username');
    const password = this.post('password');

    const admin = await this.model('user').where({username: username}).find();
    if (think.isEmpty(admin)) {
      return this.fail(401, '用户名或密码不正确');
    }
    if (think.md5(password + 'AZ_USER') !== admin.password) {
      return this.fail(400, '用户名或密码不正确');
    }

    // 更新登录信息
    await this.model('user').where({id: admin.id}).update({
      last_login_time: parseInt(Date.now() / 1000),
      last_login_ip: this.ctx.ip
    });

    const TokenSerivce = this.service('token', 'AZ');
    const sessionKey = await TokenSerivce.create({
      user_id: admin.id
    });

    if (think.isEmpty(sessionKey)) {
      return this.fail('登录失败');
    }

    const userInfo = {
      id: admin.id,
      username: admin.username,
      admin_role_id: admin.role
    };

    return this.success({token: sessionKey, userInfo: userInfo});
  }

  indexAction() {
    return this.display();
  }

  async verifyUserAction() {
    this.header('Access-Control-Allow-Origin', '*');
    this.header('Access-Control-Allow-Headers', 'Content-Type');
    this.header('Access-Control-Allow-Headers', 'X-Requested-With');
    think.token = this.get('x-az-token') || '';
    const tokenSerivce = think.service('token', 'AZ');
    think.userId = await tokenSerivce.getUserId();
    if (think.userId <= 0) {
      this.fail(400, '鉴权失败');
    } else {
      this.success('', '鉴权成功');
    }
  }
};
